<?php

namespace App\Http\Controllers\Notify;

use App\Http\Controllers\BaseController;
use App\Http\Logic\OrderLogic;
use App\Http\Requests\BjNotifyRequest;
use App\Services\AliPayService;
use Dingo\Api\Http\Request;
use Illuminate\Support\Facades\Log;

class AlipayNotifyController extends BaseController
{
    /**
     * @notes 支付宝支付分回调
     * @param BjNotifyRequest $request
     * @return \Dingo\Api\Http\Response|\Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \Alipay\OpenAPISDK\ApiException
     * @author Evil丿
     * @date 2024/09/02 17:21
     */
    public function alipayOrder(Request $request)
    {
        $params = $request->all();

        $service = new AliPayService();

        if(!$service -> verifySign($params)) {
            Log::channel('alipay')->error('alipayOrder', ['params' => $params]);

            return $this->error('验签失败','FAIL');
        }

        switch ($params["notify_type"]) {
            case 'dut_user_sign' : //授权回调
                $res = OrderLogic::editOrderState($params);
                break;
            case 'trade_status_sync' : //支付成功回调
                $res = OrderLogic::finishOrder($params,'alipay');
                break;
            default:
                $res = true;
                break;
        }

        if($res === false) {
            Log::channel('alipay')->error('alipayOrder', ['params' => $params, 'error' => $res]);

            return $this->error($res,'FAIL');
        }

        return response('success', 200);
    }

    /**
     * @notes 支付宝支付订单回调
     * @param BjNotifyRequest $request
     * @return \Dingo\Api\Http\Response|\Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \Alipay\OpenAPISDK\ApiException
     * @author Evil丿
     * @date 2024/09/03 17:37
     */
    public function alipayJsApiOrder(Request $request){
        $params = $request->all();

        $service = new AliPayService();

        if(!$service -> verifySign($params)) {
            Log::channel('alipay')->error('alipayOrder', ['params' => $params]);

            return $this->error('验签失败','FAIL');
        }

        $res = OrderLogic::finishAmountErrorOrder($params,'alipay');

        if($res !== true) {
            Log::channel('alipay')->error('alipayJsApiOrder', ['params' => $params, 'error' => $res]);

            return $this->error($res,'FAIL');
        }

        return response('success', 200);
    }

}
